package ui;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.sql.*;
import util.ConnectionUtils;

public class AppointmentListDialog extends JDialog {
    private String patientId;
    private JTable appointmentTable;
    private DefaultTableModel tableModel;

    public AppointmentListDialog(JFrame parent, String patientId) {
        super(parent, "我的预约", true);
        this.patientId = patientId;
        
        setSize(700, 500);
        setLocationRelativeTo(parent);
        setLayout(new BorderLayout(10, 10));
        
        // 创建表格
        String[] columns = {"预约号", "预约时间", "医生姓名", "科室", "职称", "状态"};
        tableModel = new DefaultTableModel(columns, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        appointmentTable = new JTable(tableModel);
        add(new JScrollPane(appointmentTable), BorderLayout.CENTER);
        
        // 创建按钮面板
        JPanel buttonPanel = new JPanel();
        JButton refreshButton = new JButton("刷新");
        JButton cancelButton = new JButton("取消预约");
        buttonPanel.add(refreshButton);
        buttonPanel.add(cancelButton);
        add(buttonPanel, BorderLayout.SOUTH);
        
        // 添加按钮事件
        refreshButton.addActionListener(e -> loadAppointments());
        cancelButton.addActionListener(e -> cancelSelectedAppointment());
        
        // 加载预约记录
        loadAppointments();
    }
    
    private void loadAppointments() {
        tableModel.setRowCount(0);
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = ConnectionUtils.getConn();
            String sql = "SELECT a.id, a.appointment_time, a.status, " +
                        "u.name as doctor_name, d.department, d.doctorRank " +
                        "FROM appointment a " +
                        "JOIN doctor d ON a.doctor_id = d.id " +
                        "JOIN user u ON d.user_id = u.id " +
                        "WHERE a.patient_id = ? " +
                        "ORDER BY a.appointment_time DESC";
            
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, patientId);
            rs = pstmt.executeQuery();
            
            while (rs.next()) {
                Object[] row = {
                    rs.getString("id"),
                    rs.getTimestamp("appointment_time"),
                    rs.getString("doctor_name"),
                    rs.getString("department"),
                    rs.getString("doctorRank"),
                    getStatusText(rs.getInt("status"))
                };
                tableModel.addRow(row);
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "加载预约记录失败：" + ex.getMessage());
        } finally {
            ConnectionUtils.close(conn, pstmt, rs);
        }
    }
    
    private void cancelSelectedAppointment() {
        int selectedRow = appointmentTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要取消的预约");
            return;
        }
        
        String appointmentId = (String) tableModel.getValueAt(selectedRow, 0);
        String status = (String) tableModel.getValueAt(selectedRow, 5);
        
        if (!"待就诊".equals(status)) {
            JOptionPane.showMessageDialog(this, "只能取消待就诊的预约！");
            return;
        }
        
        int confirm = JOptionPane.showConfirmDialog(this, 
            "确认要取消这个预约吗？", "确认取消",
            JOptionPane.YES_NO_OPTION);
            
        if (confirm == JOptionPane.YES_OPTION) {
            Connection conn = null;
            PreparedStatement pstmt = null;
            
            try {
                conn = ConnectionUtils.getConn();
                String sql = "UPDATE appointment SET status = 2 WHERE id = ? AND patient_id = ?";
                pstmt = conn.prepareStatement(sql);
                pstmt.setString(1, appointmentId);
                pstmt.setString(2, patientId);
                
                int result = pstmt.executeUpdate();
                if (result > 0) {
                    JOptionPane.showMessageDialog(this, "预约已取消");
                    loadAppointments();  // 刷新列表
                } else {
                    JOptionPane.showMessageDialog(this, "取消预约失败");
                }
            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(this, "取消预约失败：" + ex.getMessage());
            } finally {
                ConnectionUtils.close(conn, pstmt, null);
            }
        }
    }
    
    private String getStatusText(int status) {
        switch (status) {
            case 0: return "待就诊";
            case 1: return "已完成";
            case 2: return "已取消";
            default: return "未知状态";
        }
    }
} 